package com.arcpan.Service.Impl;

import cn.hutool.core.date.DateUtil;
import com.arcpan.Constant.BaseConstant;
import com.arcpan.Entity.Dto.SessionWebUserDto;
import com.arcpan.Entity.Dto.UploadResultDto;
import com.arcpan.Entity.Dto.UserSpaceDto;
import com.arcpan.Entity.Query.FileInfoQuery;
import com.arcpan.Entity.UserInfo;
import com.arcpan.Entity.Vo.FileInfo;
import com.arcpan.Exception.BaseException;
import com.arcpan.Mapper.FileInfoMapper;
import com.arcpan.Mapper.UserInfoMapper;
import com.arcpan.Result.PageResult;
import com.arcpan.Service.FileInfoService;

import com.arcpan.Util.ProcessUtils;
import com.arcpan.Util.ScaleFilter;
import com.arcpan.Util.StringTools;
import com.arcpan.component.RedisComponent;
import com.arcpan.config.AppConfig;
import com.arcpan.enums.FileDelFlagEnums;
import com.arcpan.enums.FileStatusEnums;
import com.arcpan.enums.FileTypeEnums;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class FileInfoServiceImpl implements FileInfoService {
    @Resource
    private FileInfoMapper fileInfoMapper;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private AppConfig appConfig;
    @Resource
    @Lazy
    private FileInfoServiceImpl fileInfoService;


    public PageResult getByPage(FileInfoQuery fileInfoQuery, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
//        Page<FileInfo> page= fileInfoMapper.selectByQuery(fileInfoQuery);
        System.out.println(fileInfoQuery + "file");
        Page<FileInfo> page = fileInfoMapper.selectByQuery(fileInfoQuery);
//        List<FileInfo> list=fileInfoMapper.getBylist();
        System.out.println(page);
        PageResult pageResult = new PageResult();
        pageResult.setRecords(page.getResult());
        pageResult.setTotal(page.getTotal());
        return pageResult;

    }

    @Override
    @Transactional
    public UploadResultDto uploadFile(SessionWebUserDto sessionWebUserDto, String fileId, MultipartFile file, String fileName, String filePid, String fileMd5, Integer chunkIndex, Integer chunks) {
        UploadResultDto uploadResultDto = new UploadResultDto();
        Boolean uploadsuccess = true;
        File templeFileFolder = null;
        //暂存临时目录
        String tempFolderName = appConfig.getProjectFolder() + BaseConstant.TEMP_FOLDER_FILE;
        try {

            //定义fileId
            if (StringTools.isEmpty(fileId)) {
                fileId = StringTools.getRandomNumber(BaseConstant.LENGTH_10);

            }

            uploadResultDto.setFileId(fileId);
            //查询当前时间
            Date curdate = new Date();
            //查询缓存里面的space
            UserSpaceDto userSpaceDto = redisComponent.getUserSpace(sessionWebUserDto.getUserId());

            //第一个分片
            if (chunkIndex == 0) {
                System.out.println(chunkIndex + "chunkindex");
                //第一个分片上传时候查询mds,判断数据库是否有这个文件
                FileInfoQuery fileInfoQuery = new FileInfoQuery();
                fileInfoQuery.setFileMd5(fileMd5);
                fileInfoQuery.setStatus(2);

                //只查询第一个
                PageHelper.startPage(1, 1);
                Page<FileInfo> page = fileInfoMapper.selectByQuery(fileInfoQuery);
                List<FileInfo> list = page.getResult();

                //md5值在数据库查到了，秒传
                if (!list.isEmpty()) {
                    System.out.println("12333");
                    FileInfo dfileInfo = list.get(0);
                    //判断文件大小,上传的文件大小+已使用的文件大小大于总大小
                    if (dfileInfo.getFileSize() + userSpaceDto.getUseSpace() > userSpaceDto.getTotalSpace()) {
                        throw new BaseException("网盘空间不足，请扩容");
                    }
                    System.out.println("1233334");
                    //容量足的话在数据库里把原来的文件copy一份给用户加上
                    dfileInfo.setFileId(fileId);
                    dfileInfo.setFilePid(filePid);
                    dfileInfo.setUserId(sessionWebUserDto.getUserId());
                    dfileInfo.setCreateTime(curdate);
                    dfileInfo.setLastUpdateTime(curdate);
                    dfileInfo.setStatus(2);
                    dfileInfo.setDelFlag(2);
                    dfileInfo.setFileMd5(fileMd5);
                    System.out.println("1233335");
                    //文件重命名
                    fileName = autoRename(filePid, sessionWebUserDto.getUserId(), fileName);
                    dfileInfo.setFileName(fileName);
                    System.out.println("1233335");
                    fileInfoMapper.insert(dfileInfo);
                    uploadResultDto.setStatus("upload_seconds");
                    //更新用户使用空间
                    updateUserSpace(sessionWebUserDto, dfileInfo.getFileSize());


                    return uploadResultDto;
                }

            }
            //判断磁盘空间是否足够
            Long currentTempSize = redisComponent.getFileTemplate(sessionWebUserDto.getUserId(), fileId);
            if (file.getSize() + currentTempSize + userSpaceDto.getUseSpace() > userSpaceDto.getTotalSpace()) {
                throw new BaseException("磁盘空间不足");
            }

            String currentUserFolderName = sessionWebUserDto.getUserId() + fileId;
            templeFileFolder = new File(tempFolderName + currentUserFolderName);
            if (!templeFileFolder.exists()) {
                System.out.println("创建磁盘");
                templeFileFolder.mkdirs();
                System.out.println("创建磁盘成功");
            }
            File newFile = new File(templeFileFolder.getPath() + "/" + chunkIndex);
            file.transferTo(newFile);
            System.out.println(chunkIndex + "chunks-1" + (chunks - 1));

            if (chunkIndex < chunks - 1) {

                uploadResultDto.setStatus("uploading");
                System.out.println("返回");
                redisComponent.saveFileTempSize(sessionWebUserDto.getUserId(), fileId, file.getSize());
                System.out.println("返回uploading");
                return uploadResultDto;
            }

            //最后一个分片上传完成，记录数据库，异步合并分片
            String month = DateUtil.format(new Date(), "yyyy-MM");
            System.out.println("filemonth1");
            String fileSuffix = StringTools.getFileNameSuffix(fileName);
            System.out.println("filemonth2");

            //真实文件名

            String fileRealName = currentUserFolderName + fileSuffix;
            System.out.println("fileRealName" + fileRealName);

            FileTypeEnums fileTypeEnums = FileTypeEnums.getFileTypeBySuffix(fileSuffix);
            System.out.println("filemonth4");

            //自动重命名
            fileName = autoRename(filePid, sessionWebUserDto.getUserId(), fileName);
            System.out.println("filemonth");
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileId(fileId);
            fileInfo.setUserId(sessionWebUserDto.getUserId());
            fileInfo.setFileMd5(fileMd5);
            fileInfo.setFileName(fileName);
            fileInfo.setFilePath(month + "/" + fileRealName);
            fileInfo.setFilePid(filePid);
            fileInfo.setCreateTime(curdate);
            fileInfo.setLastUpdateTime(curdate);
            fileInfo.setFileCategory(fileTypeEnums.getCategory().getCategory());
            fileInfo.setFileType(fileTypeEnums.getType());
            fileInfo.setStatus(0);
            fileInfo.setFolderType(0);
            fileInfo.setDelFlag(2);
            fileInfoMapper.insert(fileInfo);
            Long totalSize = redisComponent.getFileTemplate(sessionWebUserDto.getUserId(), fileId);
            System.out.println(totalSize + "totalSize");
            updateUserSpace(sessionWebUserDto, totalSize);
            uploadResultDto.setStatus("upload_finish");
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    System.out.println("aftercommit" + fileInfo.getFileId());
                    List<FileInfo> fileInfos1 = fileInfoMapper.getBylist();
                    System.out.println(fileInfos1 + "fileInfos");
                    fileInfoService.transfer(fileInfo.getFileId(), sessionWebUserDto);
                }
            });


            return uploadResultDto;


        } catch (Exception e) {
            System.out.println(e);
            uploadsuccess = false;
        } finally {
            if (!uploadsuccess && templeFileFolder != null) {
                try {
                    FileUtils.deleteDirectory(templeFileFolder);

                } catch (Exception e) {
                    throw new BaseException("删除临时失败");

                }
            }

        }
        return uploadResultDto;

    }

    @Async
    public void transfer(String fileId, SessionWebUserDto sessionWebUserDto) {
        System.out.println("fileId" + fileId);
        Boolean transferSuccess = true;
        String targetFilePath = null;
        String cover = null;
        FileTypeEnums fileTypeEnums = null;
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setFileId(fileId);
        fileInfoQuery.setUserId(sessionWebUserDto.getUserId());
        System.out.println("fileId" + fileInfoQuery);
        System.out.println("getUserId" + sessionWebUserDto.getUserId());

        FileInfo fileInfo = fileInfoMapper.selectByQuery1(fileInfoQuery);

        try {

            if (fileInfo == null || !fileInfo.getStatus().equals(0)) {
                return;
            }
            //   临时目录
            String tempFolderName = appConfig.getProjectFolder() + BaseConstant.TEMP_FOLDER_FILE;
            String currentUserFolderName = sessionWebUserDto.getUserId() + fileId;

            File filefolder = new File(tempFolderName + currentUserFolderName);
            System.out.println("filefolder" + filefolder);
            String fileSuffix = StringTools.getFileNameSuffix(fileInfo.getFileName());
            String month = DateUtil.format(fileInfo.getCreateTime(), "yyyy-MM");
            //目标目录
            String targetFolderName = appConfig.getProjectFolder() + BaseConstant.FILE_FOLDER_FILE;
            File targetFolder = new File(targetFolderName + "/" + month);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
            //真实的文件名
            String realFileName = currentUserFolderName + fileSuffix;
            targetFilePath = targetFolder.getPath() + "/" + realFileName;
            System.out.println(targetFilePath + "targetFilePath");
            //合并文件
            union(filefolder.getPath(), targetFilePath, fileInfo.getFileName(), true);
            //视频文件切割
            fileTypeEnums = FileTypeEnums.getFileTypeBySuffix(fileSuffix);
            System.out.println(fileTypeEnums + "fileTypeEnums");
            if (FileTypeEnums.VIDEO == fileTypeEnums) {
                System.out.println(fileTypeEnums + "fileTypeEnums1");
                cutFileVideo(fileId, targetFilePath);
                //视频生成缩略图
                cover = month + "/" + currentUserFolderName + BaseConstant.IMAGE_PNG_SIFFOX;
                String coverPath = targetFolderName + cover;
                System.out.println(coverPath + "coverPath");
                ScaleFilter.createCover4Video(new File(targetFilePath), BaseConstant.LENGTH_150, new File(coverPath));

            } else if (FileTypeEnums.IMAGE == fileTypeEnums) {
                //生成缩略图
                cover = month + "/" + realFileName.replace(".", "_.");
                String coverPath = targetFolderName + cover;
                Boolean created = ScaleFilter.createThumbnailWidthFFmpeg(new File(targetFilePath), BaseConstant.LENGTH_150, new File(coverPath), false);
                if (!created) {
                    FileUtils.copyFile(new File(targetFilePath), new File(coverPath));

                }


            }

        } catch (Exception e) {
            transferSuccess = false;
            System.out.println(e + "ee");
            throw new BaseException("文件转码失败");

        } finally {
            FileInfo updateInfo = new FileInfo();
            updateInfo.setFileSize(new File(targetFilePath).length());
            System.out.println(new File(targetFilePath).length() + "new File(targetFilePath).length()");
            updateInfo.setFileCover(cover);
            updateInfo.setFileId(fileId);
            updateInfo.setUserId(sessionWebUserDto.getUserId());
            updateInfo.setStatus(transferSuccess ? 2 : 1);
            fileInfoMapper.update(updateInfo, fileId);
//         Long count=   fileInfoMapper.updateFileStatuswithOlderStatus(fileId,sessionWebUserDto.getUserId(),updateInfo,2);
//            System.out.println(count+"count");
        }


    }

    private void cutFileVideo(String fileId, String videoFilePath) {
        File tsFolder = new File(videoFilePath.substring(0, videoFilePath.lastIndexOf(".")));
        if (!tsFolder.exists()) {
            tsFolder.mkdirs();
        }

        final String CMD_GET_CODE = "ffprobe -v error -select_streams v:0 -show_entries stream=codec_name %s";
        String cmd = String.format(CMD_GET_CODE, videoFilePath);
        String result = ProcessUtils.executeCommand(cmd, false);
        result = result.replace("\n", "");
        result = result.substring(result.indexOf("=") + 1);
        String codec = result.substring(0, result.indexOf("["));

        //转码
        if ("hevc".equals(codec)) {
            String newFileName = videoFilePath.substring(0, videoFilePath.lastIndexOf(".")) + "_" + videoFilePath.substring(videoFilePath.lastIndexOf("."));
            new File(videoFilePath).renameTo(new File(newFileName));
            String CMD_HEVC_264 = "ffmpeg -i %s -c:v libx264 -crf 20 %s";
            cmd = String.format(CMD_HEVC_264, newFileName, videoFilePath);
            ProcessUtils.executeCommand(cmd, false);
            new File(newFileName).delete();
        }

        final String CMD_TRANSFER_2TS = "ffmpeg -y -i %s  -vcodec copy -acodec copy -vbsf h264_mp4toannexb %s";
        final String CMD_CUT_TS = "ffmpeg -i %s -c copy -map 0 -f segment -segment_list %s -segment_time 30 %s/%s_%%4d.ts";

        String tsPath = tsFolder + "/" + BaseConstant.TS_NAME;
        //生成.ts
        cmd = String.format(CMD_TRANSFER_2TS, videoFilePath, tsPath);
        ProcessUtils.executeCommand(cmd, false);
        //生成索引文件.m3u8 和切片.ts
        cmd = String.format(CMD_CUT_TS, tsPath, tsFolder.getPath() + "/" + BaseConstant.M3U8_NAME, tsFolder.getPath(), fileId);
        ProcessUtils.executeCommand(cmd, false);
        //删除index.ts
        new File(tsPath).delete();


    }

    private void union(String dirpath, String toFilePath, String fileName, Boolean delSource) {
        System.out.println("union");
        File dir = new File(dirpath);
        if (!dir.exists()) {
            throw new BaseException("目录不存在");
        }
        //获取所有的分片文件
        File[] filelist = dir.listFiles();
        //创建合并后的目标文件
        File targetFile = new File(toFilePath);
        //设置使用RandomAccessFile类以读写模式来打开文件
        RandomAccessFile writeFile = null;
        try {
            //创建writeFile类，以读写的方式打开文件
            writeFile = new RandomAccessFile(targetFile, "rw");
            //设置缓冲区，临时存储数据，统一写入TargetFile文件中
            byte[] b = new byte[1024 * 10];
            //遍历所有的分片文件
            for (int i = 0; i < filelist.length; i++) {
                int len = -1;
                File chunkfile = new File(dirpath + "/" + i);
                RandomAccessFile readfile = null;
                try {
                    //尝试从chunkfile中读文件
                    readfile = new RandomAccessFile(chunkfile, "r");
                    //循环{把读取到的字节数赋值给{len}，只要结果不是-1，那么就一直读取文件}
                    while ((len = readfile.read(b)) != -1) {
                        //把b里面的数据写到target中
                        writeFile.write(b, 0, len);
                    }
                } catch (Exception e) {
                    throw new BaseException("合并分片失败");
                } finally {
                    readfile.close();
                }
            }

        } catch (Exception e) {
            throw new BaseException("合并分片失败");
        } finally {
            if (null != writeFile) {
                try {
                    writeFile.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (delSource && dir.exists()) {
                try {
                    System.out.println(dir + "dirrs");
                    FileUtils.deleteDirectory(dir);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String autoRename(String filePid, String userId, String fileName) {
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setUserId(userId);
        fileInfoQuery.setFilePid(filePid);
        fileInfoQuery.setDelFlag(2);
        fileInfoQuery.setFileName(fileName);
        Long count = fileInfoMapper.selectCount(fileInfoQuery);
        System.out.println(count + "coutn");
        if (count > 0) {
            fileName = StringTools.rename(fileName);

        }
        System.out.println(fileName + "fileName");
        return fileName;

    }

    private void updateUserSpace(SessionWebUserDto sessionWebUserDto, Long useSpace) {
        System.out.println("useSpace" + useSpace);
        Long count = fileInfoMapper.updateUserSpace(sessionWebUserDto.getUserId(), useSpace, null);
        if (count == 0) {
            throw new BaseException("网盘容量不足，请扩容");
        }
        UserSpaceDto userSpaceDto = redisComponent.getUserSpace(sessionWebUserDto.getUserId());
        userSpaceDto.setUseSpace(userSpaceDto.getUseSpace() + useSpace);
        redisComponent.saveUserSpaceuse(sessionWebUserDto.getUserId(), userSpaceDto);


    }

    public FileInfo newFolder(String filePid, String userId, String fileName) {
        checkFileName(filePid, userId, fileName, 1);
        Date curdate = new Date();
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileId(StringTools.getRandomNumber(BaseConstant.LENGTH_10));
        fileInfo.setUserId(userId);
        fileInfo.setFilePid(filePid);
        fileInfo.setFileName(fileName);
        fileInfo.setFolderType(1);
        fileInfo.setCreateTime(curdate);
        fileInfo.setLastUpdateTime(curdate);
        fileInfo.setStatus(FileStatusEnums.USING.getStatus());
        fileInfo.setDelFlag(FileDelFlagEnums.USING.getFlag());
        fileInfoMapper.insert(fileInfo);


        return fileInfo;


    }

    private void checkFileName(String filePid, String userId, String fileName, Integer folderType) {
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setFolderType(folderType);
        fileInfoQuery.setFileName(fileName);
        fileInfoQuery.setFilePid(filePid);
        fileInfoQuery.setUserId(userId);
        Integer count = Math.toIntExact(fileInfoMapper.selectCount(fileInfoQuery));
        if (count > 0) {
            throw new BaseException("此目录下已存在同名文件目录，请修改昵称");
        }


    }

    public void changeFilefolder(String fileIds, String filePid, String userId) {
        //
        if (fileIds.equals(filePid)) {
            throw new BaseException("该文件已在目录中");

        }
        //查询文件夹是否有效/被使用
        System.out.println(filePid+"filePid");
        if (!filePid.equals("0")) {
            System.out.println(filePid+"filePid1");
            FileInfoQuery fileInfoQuery = new FileInfoQuery();
            fileInfoQuery.setFileId(filePid);
            fileInfoQuery.setUserId(userId);
            FileInfo fileInfo = fileInfoMapper.selectByQuery1(fileInfoQuery);
            if (fileInfo == null || !FileDelFlagEnums.USING.getFlag().equals(fileInfo.getDelFlag())) {
                throw new BaseException("参数错误");
            }
        }
        //查询文件夹下的filelist
        String[] fileIdArray = fileIds.split(",");
        FileInfoQuery fileInfoQuerys = new FileInfoQuery();
        fileInfoQuerys.setFilePid(filePid);
        fileInfoQuerys.setUserId(userId);
        List<FileInfo> dblist = fileInfoMapper.selectByQuery2(fileInfoQuerys);
        Map<String, FileInfo> dbfileMap = dblist.stream().collect(Collectors.toMap(FileInfo::getFileName, Function.identity(), (file1, file2) -> file2));
        System.out.println(dbfileMap + "dbfileMap");
        //查询选中的文件
        fileInfoQuerys = new FileInfoQuery();
        fileInfoQuerys.setUserId(userId);
        fileInfoQuerys.setFileIdArray(fileIdArray);
        List<FileInfo> list = fileInfoMapper.selectByQuery2(fileInfoQuerys);
        System.out.println(list + "list");
        //将所选文件批量传入重命名
        for (FileInfo item : list) {
            FileInfo rootfileInfo = dbfileMap.get(item.getFileName());
            //文件名已存在，重命名呗还原的文件名
            FileInfo updateInfo = new FileInfo();
            if (rootfileInfo != null) {
                String fileName = StringTools.rename(rootfileInfo.getFileName());
                updateInfo.setFileName(fileName);

            }
            updateInfo.setFilePid(filePid);
            updateInfo.setUserId(userId);
            fileInfoMapper.update(updateInfo, item.getFileId());

        }


    }

    @Transactional(rollbackFor = Exception.class)
    public FileInfo rename(String fileId, String userId, String fileName) {
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setFileId(fileId);
        fileInfoQuery.setUserId(userId);
        FileInfo fileInfo = fileInfoMapper.selectByQuery1(fileInfoQuery);
        if (null == fileInfo) {
            throw new BaseException("文件不存在");
        }
        String filePid = fileInfo.getFilePid();
        checkFileName(filePid, userId, fileName, fileInfo.getFolderType());
        if (fileInfo.getFolderType().equals(0)) {
            fileName = fileName + StringTools.getFileNameSuffix(fileInfo.getFileName());

        }
        Date curdate = new Date();
        FileInfo dbinfo = new FileInfo();
        dbinfo.setFileName(fileName);
        dbinfo.setUserId(userId);
        dbinfo.setLastUpdateTime(curdate);
        fileInfoMapper.update(dbinfo, fileId);
        FileInfoQuery fileInfoQuery1 = new FileInfoQuery();
        fileInfoQuery1.setFileId(fileId);
        fileInfoQuery1.setUserId(userId);
        fileInfoQuery1.setFileName(fileName);
        Integer count = Math.toIntExact(fileInfoMapper.selectCount(fileInfoQuery1));
        if (count > 1) {
            throw new BaseException("文件" + fileName + "已存在");
        }
        fileInfo.setFileName(fileName);
        fileInfo.setLastUpdateTime(curdate);
        return fileInfo;

    }

    public void removeFile(String fileIds, String userId) {
        String[] fileIdArray = fileIds.split(",");
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setFileIdArray(fileIdArray);
        fileInfoQuery.setUserId(userId);
        fileInfoQuery.setDelFlag(FileDelFlagEnums.USING.getFlag());
        List<FileInfo> list = fileInfoMapper.selectByQuery2(fileInfoQuery);
        if (list.isEmpty()) {
            return;
        }
        List<String> delFilepidlist = new ArrayList<>();
        for (FileInfo fileInfo : list) {
            findalldellist(delFilepidlist, userId, fileInfo.getFileId(), FileDelFlagEnums.USING.getFlag());
        }
        if (!delFilepidlist.isEmpty()) {
            FileInfo updateinfo = new FileInfo();
            updateinfo.setDelFlag(FileDelFlagEnums.DEL.getFlag());
            fileInfoMapper.updateFileDel(updateinfo, userId, delFilepidlist, null, FileDelFlagEnums.USING.getFlag());
        }
        //选中的文件更新欸回收站
        List<String> delFileIdlist = Arrays.asList(fileIdArray);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setRecoveryTime(new Date());
        fileInfo.setDelFlag(FileDelFlagEnums.RECYCLE.getFlag());
        fileInfoMapper.updateFileDel(fileInfo, userId, null, delFileIdlist, FileDelFlagEnums.USING.getFlag());


    }

    private void findalldellist(List<String> fileIdList, String userId, String fileId, Integer delFlag) {
        fileIdList.add(fileId);
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setUserId(userId);
        fileInfoQuery.setFilePid(fileId);
        fileInfoQuery.setDelFlag(delFlag);
        fileInfoQuery.setFolderType(1);
        List<FileInfo> list = fileInfoMapper.selectByQuery2(fileInfoQuery);
        for (FileInfo fileInfo : list) {
            findalldellist(fileIdList, userId, fileInfo.getFileId(), delFlag);

        }

    }

    public void deletefile(String userId, String fileIds) {
        String[] fileidarray = fileIds.split(",");
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setFileIdArray(fileidarray);
        fileInfoQuery.setUserId(userId);
        fileInfoQuery.setDelFlag(1);
        List<FileInfo> list = fileInfoMapper.selectByQuery2(fileInfoQuery);
        List<String> dellist = new ArrayList<>();
        for (FileInfo fileInfo : list) {
            if (fileInfo.getFolderType().equals(1)) {
                findalldellist(dellist, userId, fileInfo.getFileId(), FileDelFlagEnums.DEL.getFlag());
            }
        }
        if (!dellist.isEmpty()) {
            fileInfoMapper.delFileDel(userId, dellist, null, FileDelFlagEnums.DEL.getFlag());
        }
        fileInfoMapper.delFileDel(userId,null,Arrays.asList(fileidarray),FileDelFlagEnums.RECYCLE.getFlag());
        Long useSpace=fileInfoMapper.selectUseSpace(userId);
        UserInfo userInfo=new UserInfo();
        userInfo.setUseSpace(useSpace);
        userInfoMapper.updateByUserId(userInfo,userId);
        UserSpaceDto userSpaceDto=redisComponent.getUserSpace(userId);
        userSpaceDto.setUseSpace(useSpace);
        redisComponent.saveUserSpaceuse(userId,userSpaceDto);
    }

    public void recoverfile(String userId, String fileIds) {
        //查询回收中的文件
        String[] fileIdArray = fileIds.split(",");
        FileInfoQuery fileInfoQuery = new FileInfoQuery();
        fileInfoQuery.setUserId(userId);
        fileInfoQuery.setFileIdArray(fileIdArray);
        fileInfoQuery.setDelFlag(FileDelFlagEnums.RECYCLE.getFlag());
        List<FileInfo> fileInfoList = fileInfoMapper.selectByQuery2(fileInfoQuery);
        List<String> delfile = new ArrayList<>();
        System.out.println("1234");
        for (FileInfo fileInfo : fileInfoList) {
            if (fileInfo.getFolderType().equals(1)) {
                findalldellist(delfile, userId, fileInfo.getFileId(), FileDelFlagEnums.DEL.getFlag());
            }
        }
        System.out.println("12341");
        //查询所有根目录下的文件
        FileInfoQuery fileInfoQuery1 = new FileInfoQuery();
        fileInfoQuery1.setUserId(userId);
        fileInfoQuery1.setDelFlag(FileDelFlagEnums.USING.getFlag());
        fileInfoQuery1.setFilePid("0");
        List<FileInfo> allrootlist = fileInfoMapper.selectByQuery2(fileInfoQuery1);
        Map<String, FileInfo> rootfilemap = allrootlist.stream().collect(Collectors.toMap(FileInfo::getFileName, Function.identity(), (data1, data2) -> data2));
        //查询所有所选文件将目录下的所有文件更新为使用中
        if (!delfile.isEmpty()) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setDelFlag(FileDelFlagEnums.USING.getFlag());
            fileInfoMapper.updateFileDel(fileInfo, userId, delfile, null, FileDelFlagEnums.DEL.getFlag());
            System.out.println("12343");
        }
        //选中文件还原
        List<String> delFileIdList = Arrays.asList(fileIdArray);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setDelFlag(FileDelFlagEnums.USING.getFlag());
        fileInfo.setFilePid("0");
        fileInfo.setLastUpdateTime(new Date());
        fileInfoMapper.updateFileDel(fileInfo, userId, null, delFileIdList, FileDelFlagEnums.RECYCLE.getFlag());
        System.out.println("12344");
        //所选文件重命名
        for (FileInfo fileInfo1 : fileInfoList) {
            FileInfo rootfileIndo = rootfilemap.get(fileInfo1.getFileName());
            //文件已经存在，重命名
            FileInfo updateInfo = new FileInfo();
            if (rootfileIndo != null) {
                String fileName = StringTools.rename(fileInfo1.getFileName());
                updateInfo.setFileName(fileName);
                System.out.println("12345");
                updateInfo.setUserId(userId);
                fileInfoMapper.update(updateInfo, fileInfo1.getFileId());
            }



        }

    }

}
